package com.example.xgsweather.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.KeyEvent;
import android.widget.Toast;

import androidx.core.view.GravityCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.example.xgsweather.R;
import com.example.xgsweather.db.FrequentlyUsedCity;
import com.example.xgsweather.fragment.WeatherFragment;
import com.example.xgsweather.service.WeatherNotificationsService;
import com.example.xgsweather.util.LogUtil;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;

public class WeatherFragmentActivity extends BaseActivity {

    private static final String TAG = "WeatherFragmentActivity测试";

    /**
     * 当前城市的天气id
     */
    public String mWeatherId;
    /**
     * 当前城市的名字
     */
    public String mCountyName;
    /**
     * 当前选中显示的 WeatherFragment
     */
    public WeatherFragment mWeatherFragment;
    /**
     * 当前选中的列表索引号
     */
    public int mPosition;

    private ViewPager viewPager;
    final List<WeatherFragment> weatherFragmentList = new ArrayList<>();
    List<FrequentlyUsedCity> frequentlyUsedCities = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weather_fragment);
        mWeatherId = getIntent().getStringExtra("weather_id");
        mCountyName = getIntent().getStringExtra("county_name");
        mPosition = getIntent().getIntExtra("position", 0);
        LogUtil.w(TAG + "onCreate()：id:" + mWeatherId + "，name:" + mCountyName + "，p:" + mPosition);

        frequentlyUsedCities = LitePal.findAll(FrequentlyUsedCity.class);
        if (frequentlyUsedCities.size() == 0) {
            new FrequentlyUsedCity(mWeatherId, mCountyName).save();
            frequentlyUsedCities = LitePal.findAll(FrequentlyUsedCity.class);
        }
        for (int i = 0; i < frequentlyUsedCities.size(); i++) {
            // 向WeatherFragment传递数据（不建议使用构造方法，否则横竖屏切换会空指针异常）
            Bundle bundle = new Bundle();
            bundle.putString("weather_id", frequentlyUsedCities.get(i).getWeatherId());
            bundle.putString("county_name", frequentlyUsedCities.get(i).getCityName());
            WeatherFragment weatherFragment = new WeatherFragment();
            weatherFragment.setArguments(bundle);
            weatherFragmentList.add(weatherFragment);
        }
        if (weatherFragmentList.size() <= mPosition) {
            mPosition = weatherFragmentList.size() - 1;
        }
        mWeatherFragment = weatherFragmentList.get(mPosition);
        updateSharedPreferences();

        viewPager = findViewById(R.id.weather_fragment_vp);
        viewPager.setAdapter(new FragmentStatePagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return weatherFragmentList.get(position);
            }

            @Override
            public int getCount() {
                return weatherFragmentList.size();
            }
        });

        // 设置当前显示页,需写在OnPageChangeListener前面，否则启动app时会出现缓存为null的bug
        viewPager.setCurrentItem(mPosition);

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            /**
             * 页面滑动状态停止前一直调用
             * @param position 当前点击滑动页面的位置
             * @param positionOffset 当前页面偏移的百分比
             * @param positionOffsetPixels 当前页面偏移的像素位置
             */
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                // LogUtil.d(TAG + "vp：滑动中 —-> position:" + position + "   positionOffset:" + positionOffset + "   positionOffsetPixels:" + positionOffsetPixels);
            }

            /**
             * 滑动后显示的页面和滑动前不同，调用
             * @param position 选中显示页面的位置
             */
            @Override
            public void onPageSelected(int position) {
                LogUtil.w("vp：显示页改变 —-> position:" + position);
                mWeatherFragment = weatherFragmentList.get(position);
                mWeatherId = mWeatherFragment.mWeatherId;
                mCountyName = mWeatherFragment.mCountyName;
                mPosition = position;
                LogUtil.w("显示页改变：id:" + mWeatherId + "，name:" + mCountyName + "，p:" + mPosition);
                updateSharedPreferences();
            }

            /**
             * 页面状态改变时调用
             * SCROLL_STATE_IDLE：空闲状态
             * SCROLL_STATE_DRAGGING：滑动状态
             * SCROLL_STATE_SETTLING：滑动后滑翔的状态
             * @param state 当前页面的状态
             */
            @Override
            public void onPageScrollStateChanged(int state) {
                switch (state) {
                    case ViewPager.SCROLL_STATE_IDLE:
                        // LogUtil.d(TAG + "vp：状态改变 —-> SCROLL_STATE_IDLE ==== 静止状态");
                        break;
                    case ViewPager.SCROLL_STATE_DRAGGING:
                        // LogUtil.d(TAG + "vp：状态改变 —-> SCROLL_STATE_DRAGGING == 滑动状态");
                        break;
                    case ViewPager.SCROLL_STATE_SETTLING:
                        // LogUtil.d(TAG + "vp：状态改变 —-> SCROLL_STATE_SETTLING == 滑翔状态");
                        break;
                }
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        // 减少由于网络延迟导致写入缓存为空的情况
        new Handler(getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
                updateSharedPreferences();
            }
        }, 10000);
    }

    public void requestWeatherForQWeather(String newWeatherId, String newCountyName) {
        LogUtil.w(TAG + "requestWeatherForQWeather()（切换城市）：" + newCountyName + "：" + newWeatherId);

        String oldWeatherId = mWeatherId;
        String oldCountyName = mCountyName;

        mWeatherId = newWeatherId;
        mCountyName = newCountyName;

        mWeatherFragment.drawerLayout.closeDrawers();
        mWeatherFragment.swipeRefresh.setRefreshing(true);
        mWeatherFragment.mWeatherId = mWeatherId;
        mWeatherFragment.mCountyName = mCountyName;
        mWeatherFragment.requestWeatherForQWeather(newWeatherId);

        LogUtil.w("更新数据：oldCountyName=" + oldCountyName + ", newCountyName=" + newCountyName);
        int result = new FrequentlyUsedCity(mWeatherId, mCountyName).updateAll("weatherId = ? and cityName = ?", oldWeatherId, oldCountyName);
        LogUtil.w("更新数据：" + result);

        frequentlyUsedCities = LitePal.findAll(FrequentlyUsedCity.class);
        updateSharedPreferences();
    }

    /**
     * 更新缓存
     */
    private void updateSharedPreferences() {
        LogUtil.w("updateSharedPreferences:" + mCountyName);
        // 将当前显示的城市缓存到SharedPreferences当中
        SharedPreferences.Editor editor = getSharedPreferences("current_city", Context.MODE_PRIVATE).edit();
        editor.putString("weather_id", mWeatherId);
        editor.putString("county_name", mCountyName);
        editor.putInt("position", mPosition);
        editor.putString("temperature", mWeatherFragment.getDegree());
        editor.putString("description", mWeatherFragment.getWeatherInfo());
        editor.apply();
        // 启动服务在通知栏显示当前城市天气信息
        Intent intent = new Intent(this, WeatherNotificationsService.class);
        intent.putExtra("weather_id", mWeatherId);
        intent.putExtra("county_name", mCountyName);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //startForegroundService(intent);
        } else {
            //startService(intent);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            try {
                if (mWeatherFragment.drawerLayout.isDrawerOpen(GravityCompat.START)) {
                    mWeatherFragment.drawerLayout.closeDrawers();
                    return true;
                }
                exit();
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    // 定义一个变量，来标识是否退出
    private static boolean isExiting = false;

    private void exit() {
        if (isExiting) {
            super.onBackPressed();
        } else {
            isExiting = true;
            Toast.makeText(getApplicationContext(), "再按一次返回退出程序", Toast.LENGTH_SHORT).show();
            // 利用handler延迟发送更改状态信息
            new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                @Override
                public void run() {
                    isExiting = false;
                }
            }, 1500);
        }
    }

}
